package com.ewhale.feitengguest.ui.user.task;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ewhale.feitengguest.R;
import com.ewhale.feitengguest.presenter.user.task.MsgBoardPresenter;
import com.ewhale.feitengguest.ui.user.task.adapter.PublicPicAdapter;
import com.ewhale.feitengguest.utils.PictureUtils;
import com.ewhale.feitengguest.utils.QiniuUtils;
import com.ewhale.feitengguest.view.user.task.MsgBoardView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.simga.library.activity.MBaseActivity;
import com.simga.library.utils.CheckUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MsgBoardActivity extends MBaseActivity<MsgBoardPresenter> implements MsgBoardView, EasyPermissions.PermissionCallbacks {
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.gv_image)
    RecyclerView gvImage;

    private PublicPicAdapter mAdapter;
    private List<String> images = new ArrayList<>();
    private long missionId;
    private static final int REQUEST_CODE_PERMISSION_2 = 10002;
    private static final int REQUEST_CODE_CHOOSE_IMAGE = 1000;


    public static void open(MBaseActivity mContext, long missionId) {
        Bundle bundle = new Bundle();
        bundle.putLong("missionId", missionId);
        mContext.startForResult(bundle, 1005,MsgBoardActivity.class);
    }

    @Override
    protected void onGetBundle(Bundle bundle) {
        missionId = bundle.getLong("missionId");
    }

    @Override
    protected int getViewId() {
        return R.layout.activity_msg_board;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mAdapter = new PublicPicAdapter(images, 3);
        gvImage.setAdapter(mAdapter);
        GridLayoutManager manager = new GridLayoutManager(mContext,3);
        gvImage.setLayoutManager(manager);
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    @Override
    protected void initListener() {
        mAdapter.setOnItemClickListener(new PublicPicAdapter.onItemClickListener() {
            @Override
            public void onDelete(int position) {
                images.remove(position);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onItemClick(int position) {
                if (images.size() == 3) {
                    return;
                }
                if (position == images.size()) {
                    requestPermissionMain();
                }
            }
        });
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (CheckUtil.isNull(etContent.getText().toString())) {
                    tvRight.setEnabled(false);
                } else {
                    tvRight.setEnabled(true);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_2)
    private void requestPermissionMain() {
        String[] perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            PictureUtils.openAluamMore(this, REQUEST_CODE_CHOOSE_IMAGE, 3 - images.size());
        } else {
            EasyPermissions.requestPermissions(this, "申请获取相关权限",
                    REQUEST_CODE_PERMISSION_2, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        PictureUtils.openAluamMore(this, requestCode, 3 - images.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("权限申请")
                    .setRationale("申请获取相关权限")
                    .setPositiveButton(getString(R.string.comfir))
                    .setNegativeButton(getString(R.string.cancle))
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_CHOOSE_IMAGE) {
            List<String> image = new ArrayList<>();
            for (LocalMedia media : PictureSelector.obtainMultipleResult(data)) {
                image.add(media.getCompressPath());
            }
            showLoading();
            QiniuUtils.uploadImage(image, keys -> {
                dismissLoading();
                images.addAll(keys);
                mAdapter.notifyDataSetChanged();
                PictureUtils.clearCache(mContext);
            });
        }
    }

    @Override
    public void showProLoading() {
        showLoading();
    }

    @Override
    public void dimissProLoading() {
        dismissLoading();
    }

    @Override
    public void showErrorMessage(int postCode, String code, String message) {
        showErrorMsg(code, message);
    }


    @OnClick({R.id.iv_back, R.id.tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_right:
                String content = etContent.getText().toString();
                StringBuffer buffer = new StringBuffer();
                for (String str : images) {
                    buffer.append(str);
                    buffer.append(",");
                }
                presenter.commitMessage(missionId, content, CheckUtil.isNull(buffer.toString()) ? "" : buffer.toString().substring(0, buffer.toString().length() - 1));
                break;
        }
    }

    @Override
    public void commitSuccess() {
        showToast("留言提交成功");
        finishResult();
    }
}
